
    /**  
    * @Title: RedissonDistributedLocker.java
    * @Package com.efast.cafe.framework.redis.locker
    * @Description: TODO(用一句话描述该文件做什么)
    * @author Administrator
    * @date 2019年1月17日
    * @version V1.0  
    */
    
package com.efast.cafe.framework.redis.locker;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

/**
    * @ClassName: RedissonDistributedLocker
    * @Description: 分布式锁
    * @author xuanming.feng
    * @date 2019年1月17日
    *
    */
public class RedissonDistributedLocker{

	private RedissonClient redissonClient;
	
	public RedissonDistributedLocker(RedissonClient redissonClient){
		this.redissonClient = redissonClient;
	}

	/**
     * 加锁
     * @param lockKey
     * @return
     */
    public RLock lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return lock;
    }

    /**
     * 带超时的锁
     * @param lockKey
     * @param timeout 超时时间   单位：秒
     */
    public RLock lock(String lockKey, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        lock.expire(leaseTime, TimeUnit.SECONDS);
        return lock;
    }
    
    /**
     * 带超时的锁
     * @param lockKey
     * @param unit 单位
     * @param timeout 超时时间 
     */
    public RLock lock(String lockKey, TimeUnit unit ,int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        lock.expire(timeout, unit);
        return lock;
    }
    
    /**
     * 尝试获取锁
     * @param lockKey
     * @param unit 等待时间和自动释放锁的单位
     * @param waitTime 最多等待时间
     * @param leaseTime 上锁后自动释放锁时间
     * @return
     */
    public boolean tryLock(String lockKey, int waitTime, int leaseTime,TimeUnit unit) {
        try {
        	RLock lock = redissonClient.getLock(lockKey);
            return lock.tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            return false;
        }
    }
    
    /**
     * 尝试获取锁
     * @param lockKey
     * @param waitTime 最多等待时间  默认单位：秒
     * @param leaseTime 上锁后自动释放锁时间  默认单位：秒
     * @return
     */
    public boolean tryLock(String lockKey,int waitTime, int leaseTime) {
        try {
        	RLock lock = redissonClient.getLock(lockKey);
            return lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }
    
    
    /**
     * 释放锁
     * @param lockKey
     */
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        if(lock.isHeldByCurrentThread()){
        	 lock.unlock();
        }
       
    }
    /**
     * 释放锁
     * @param lock
     */
    public void unlock(RLock lock) {
    	if(lock.isHeldByCurrentThread()){
    		 lock.unlock();
    	}
       
    }
}
